/**
 * @file 添加文章
 * @author wangshaozhi(wangshaozhi@baidu.com)
 */

import {observer} from "mobx-react";
import {useEffect, useRef} from "react";
import {useLocation} from "react-router-dom";
import request from '../../../../request';
import qs from 'querystring';

import {ARTICLE_DETAIL_URL} from "../../../../request/url";
import Article from "../../../../model/article";

// store
import {MainStore} from "../../../../store/mainStore";

// components
import {Header} from "./Header";
import {Content} from "./Content";

// style
import cls from './index.module.scss';

interface IProps {
    store: MainStore;
}

export const AddArticle: React.FC<IProps> = observer(({
    store
}) => {
    const {articleStore} = store;
    const {search} = useLocation();
    const getArticleByIdRef = useRef<boolean>(true);

    useEffect(() => {
        const {id} = qs.parse(search.substring(1));
        const getArticleById = async () => {
            try {
                const res = await request({
                    method: 'post',
                    url: ARTICLE_DETAIL_URL,
                    data: {
                        id: +id!
                    }
                });
                const {
                    code
                } = res.data;
                if (code === 0) {
                    articleStore.update({
                        currOperateArticle: new Article({...res.data.article})
                    });
                }
            }
            catch (e) {

            }
        }
        if (!!id && getArticleByIdRef.current) {
            getArticleById();
            getArticleByIdRef.current = false;
        }
        else {
            articleStore.update({
                currOperateArticle: new Article({
                    publishTime: new Date().toLocaleDateString()
                })
            })
        }
    }, [search, articleStore]);

    return (
        <div className={cls.wrapper}>
            <Header store={store} />
            <Content store={store} />
        </div>
    );
})